package com.sumainfor.zuul.service.impl;

import com.sumainfor.common.util.ContextUtils;
import com.sumainfor.common.util.FieldCheckUtil;
import com.sumainfor.common.util.JsonResult;
import com.sumainfor.common.utlis.ParamsCommon;
import com.sumainfor.common.wechat.WxConstant;
import com.sumainfor.zuul.dao.WxSysUserMapper;
import com.sumainfor.zuul.entity.SysUserEntity;
import com.sumainfor.zuul.util.wechat.AuthUtil;
import org.apache.commons.collections.MapUtils;
import org.apache.http.client.ClientProtocolException;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import net.sf.json.JSONObject;

/**
 * 功能描述:
 *
 * @Auther: zhlu
 * @Date: 2019/1/25 21:04
 * @Description:
 */
@Service
public class WxSysUserService {
    Logger log = LoggerFactory.getLogger(WxSysUserService.class);
    @Autowired
    WxSysUserMapper sysUserMapper;

    /**
     * 功能描述:
     * 根据用户编号和code获取用户资料并且保存下来
     *
     * @Author zhlu
     * @Description //TODO
     * @Date 2019/1/25 21:05
     */
    @Transactional(rollbackFor = Exception.class)
    public JsonResult BoundSysUserWechat(Map<String, Object> params) throws ClientProtocolException, IOException {
        JsonResult result = new JsonResult();
        //所有新增处理
        Map<String, Object> commonInsertParms = new HashMap<String, Object>();


        SysUserEntity entity = (SysUserEntity) SecurityUtils.getSubject().getPrincipal();

        commonInsertParms.put("by", entity.getUserId());//操作人
        commonInsertParms.put("term", "8");// 创建端 Insert端： 1 租客端 2市场部 3 工程部   4运营部   5财务部  6总经办 7发展部 8IT部
        commonInsertParms.put("fnc",
                this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
        ParamsCommon.commonInsertParms(commonInsertParms);
        //修改处理
        Map<String, Object> commonUpdateParms = new HashMap<String, Object>();
        commonUpdateParms.put("by", MapUtils.getInteger(params, "userId"));//操作人
        commonUpdateParms.put("term", "8");// 创建端 Insert端： 1 租客端 2市场部 3 工程部   4运营部   5财务部  6总经办 7发展部
        commonUpdateParms.put("fnc",
                this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
        ParamsCommon.commonUpdateParms(commonUpdateParms);

        try {
            String code = params.get("code").toString();
            String url = WxConstant.WECHATPAY_OAUTH2_URI
                    + "appid=" + WxConstant.WECHATPAY_APPID
                    + "&secret=" + WxConstant.WECHATPAY_PAY_APPSECRET
                    + "&code=" + code
                    + "&grant_type=authorization_code";

            JSONObject jsonObject = AuthUtil.doGetJson(url);
            String openid = jsonObject.getString("openid");
            String token = jsonObject.getString("access_token");

            String infoUrl = "https://api.weixin.qq.com/sns/userinfo?"
                    + "access_token=" + token
                    + "&openid=" + openid
                    + "&lang=zh_CN";
            JSONObject infoUrls = AuthUtil.doGetJson(infoUrl);

            log.info("-------------------------------------------------------------------------------------------------");
            log.info("-------------------------------------------------------------------------------------------------");
            log.info("-------------------------------------------------------------------------------------------------");
            log.info("-------------------------------------------------------------------------------------------------");
            log.info("---" + infoUrls);

            //根据openID获取用户资料
            Map<String,Object>user=sysUserMapper.getOpenIdUser(new HashMap<String,Object>(){{
                put("popenid",openid);
            }});
            //判断当前用户是否已绑定，如果绑定直接返回出去
            if(MapUtils.isNotEmpty(user)){
                return result.putFailed("当前微信用户已绑定");
            }
            //判断该openID是否绑定了用户
            Map<String, Object> is = new HashMap<String, Object>();
            is.put("popenid", openid);
            is.put("unionid", infoUrls.get("unionid"));
            is.put("sex", infoUrls.get("sex"));
            is.put("headimgurl", infoUrls.get("headimgurl"));
            is.put("nickname", infoUrls.get("nickname"));
            is.put("country", infoUrls.get("country"));
            is.put("province", infoUrls.get("province"));
            is.put("city", infoUrls.get("city"));
            //根据当前用户编号绑定openID
            log.info("params===========>"+params);
            sysUserMapper.BoundSysUserWechat(new HashMap<String, Object>() {{
                putAll(commonUpdateParms);
                put("UserId", params.get("UserId"));
                put("popenid",openid);
                put("unionid",infoUrls.get("unionid"));
            }});
            //根据openID获取用户资料
            sysUserMapper.AddSysUserWx(new HashMap<String, Object>() {{
                putAll(commonInsertParms);
                putAll(is);
                put("UserId", params.get("UserId"));
            }});
            result.putSuccess("绑定成功！");
        } catch (ClientProtocolException clientProtocolException) {
            clientProtocolException.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return result;
    }

    /**
     * 功能描述: 
     * 根据用户扫码code获取微信openID然后查询用户资料
     * @Author zhlu
     * @Description //TODO
     * @Date 2019/1/26 19:08
     */
    public Map<String,Object>getOpenIdUser(Map<String,Object>params) throws ClientProtocolException, IOException{
        Map<String,Object>result=new HashMap<String,Object>();
        //根据code获取微信资料
        String code = params.get("code").toString();
        String url = WxConstant.WECHATPAY_OAUTH2_URI
                + "appid=" + WxConstant.WECHATPAY_APPID
                + "&secret=" + WxConstant.WECHATPAY_PAY_APPSECRET
                + "&code=" + code
                + "&grant_type=authorization_code";

        JSONObject jsonObject = AuthUtil.doGetJson(url);
        log.info("----------------------------------------");
        log.info("----------------------------------------");
        log.info("----------pcopenId-------------"+jsonObject);
        log.info("----------------------------------------");
        String openid = jsonObject.getString("openid");
        //根据openID获取用户资料
        Map<String,Object>user=sysUserMapper.getOpenIdUser(new HashMap<String,Object>(){{
            put("popenid",openid);
        }});
        if(!FieldCheckUtil.isMapFieldNotNull(user, new String[]{"UserId"})||
                !FieldCheckUtil.isMapFieldNotNull(user, new String[]{"delfg"})){
            result.put("errorCode","1");
        }else{
            Integer delfg= (Integer) user.get("delfg");
            if(delfg==0){
                result.put("UserId",user.get("UserId"));
                result.put("errorCode","0");
            }else if(delfg==1){
                result.put("errorCode","2");
            }
        }
        return result;
    }

}
